<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>添加--${site.name}</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="description" content="${site.description}"/>
    <meta name="keywords" content="${site.keywords}"/>
    <meta name="author" content="${site.author}"/>
    <link rel="icon" href="${site.logo}">
    <link rel="stylesheet" href="${base}/static/layui/css/layui.css" media="all"/>
    <style type="text/css">
        .layui-form-item .layui-inline {
            width: 33.333%;
            float: left;
            margin-right: 0;
        }

        @media (max-width: 1240px) {
            .layui-form-item .layui-inline {
                width: 100%;
                float: none;
            }
        }

        .layui-form-item .role-box {
            position: relative;
        }

        .layui-form-item .role-box .jq-role-inline {
            height: 100%;
            overflow: auto;
        }

    </style>
</head>
<body class="childrenBody">
<form class="layui-form" lay-filter="form" style="width:80%;">
    <input value="" name="id" type="hidden">
    <input value="" name="videoUrl" id="videoUrl" type="hidden">
    <video id="videoattr" style="display: none"></video>
    <div class="layui-form-item">
        <label class="layui-form-label">知识点名称</label>
        <div class="layui-input-block">
            <input type="text" class="layui-input submitlist" autocomplete="off" name="lorePointName" id="lorePointName"
                   value="" placeholder="请填写知识点名称" lay-verify="required">
            <input type="hidden" name="id" id="id">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">知识点描述</label>
        <div class="layui-input-block">
            <textarea name="lorePointDescribe" id="lorePointDescribe" placeholder="请填写知识点描述" lay-verify="required"
                      class="layui-textarea submitlist"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">所属课程</label>
        <div class="layui-input-block">
            <select name="courseId" id="courseId" class="submitlist" lay-verify="required" lay-filter="course">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">所属单元</label>
        <div class="layui-input-block">
            <select name="unitId" id="unitId" class="submitlist" lay-verify="required" lay-filter="unit">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">所属章节</label>
        <div class="layui-input-block">
            <select name="sectionId" id="sectionId" class="submitlist" lay-verify="required" lay-filter="section">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">激活状态</label>
        <div class="layui-input-block">
            <select name="isActivated" class="submitlist" id="isActivated" lay-verify="required">
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">知识点视频</label>
        <div class="layui-upload margin-left-110 layui-input-block">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm submitlist" type="button" id="selectvedio">选择文件</button>
            </div>
            <div class="layui-upload-list">
                <table class="layui-table">
                    <thead>
                    <tr>
                        <th>文件名</th>
                        <th>大小</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="upList"></tbody>
                </table>
            </div>
        </div>
    </div>


    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn submitlist" lay-submit="" lay-filter="addChLorePoint">立即提交</button>
            <button type="reset submitlist" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<script type="text/javascript" src="${base}/static/layui/layui.js"></script>
<script type="text/javascript" src="${base}/static/js/qiniu.min.js"></script>
<script>
    layui.use(['form', 'jquery', 'layer', 'upload'], function () {
        var form = layui.form,
            $ = layui.jquery,
            layer = layui.layer,
            upload = layui.upload;

        /**
         * 加载状态
         */
        $.get("${base}/admin/system/dict/getDictByType/is_activated", {}, function (data) {
            var html = "";
            if (data.success === true) {
                for (var i = 0; i < data.data.length; i++) {
                    html += '<option value="' + data.data[i].value + '">' + data.data[i].label + '</option>';
                }
                $("#isActivated").html(html);
                form.val('form', {
                    "isActivated": 1
                });
                //表单重新渲染
                form.render();
            }
        }, "json");

        /**
         * 加载课程列表
         */
        $.post("${base}/chCourse/getCourseClass", {}, function (data) {
            var html = "<option value=\"\">请选择课程</option>";
            for (var i = 0; i < data.length; i++) {
                html += '<option value="' + data[i].id + '">' + data[i].courseName + '</option>';
            }
            $("#courseId").html(html);
            //表单重新渲染
            form.render();
        }, "json");

        /**
         * 监听form-select事件
         */
        form.on("select(course)", function () {
            var courseId = $("#courseId").val();
            if (courseId == "") return false;
            /**
             * 加载单元列表
             */
            $.post("${base}/chUnit/getUnitClass", {courseId: courseId}, function (data) {
                var html = "<option value=\"\">请选择单元</option>";
                for (var i = 0; i < data.length; i++) {
                    html += '<option value="' + data[i].id + '">' + data[i].unitName + '</option>';
                }
                $("#unitId").html(html);
                //表单重新渲染
                form.render();
            }, "json");
        });
        /**
         * 监听form-select事件
         */
        form.on("select(unit)", function () {
            var unitId = $("#unitId").val();
            if (unitId == "") return false;
            /**
             * 加载章节列表
             */
            $.post("${base}/chSection/getSectionClass", {unitId: unitId}, function (data) {
                var html = "<option value=\"\">请选择章节</option>";
                for (var i = 0; i < data.length; i++) {
                    html += '<option value="' + data[i].id + '">' + data[i].sectionName + '</option>';
                }
                $("#sectionId").html(html);
                //表单重新渲染
                form.render();
            }, "json");
        });


        //初始化文件上传事件（七牛云）
        var uploadListIns = upload.render({
            elem: "#selectvedio",
            accept: "video",
            multiple: false,
            auto: false,
            choose: function (obj) {
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function (index, file, result) {
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td id = "vediotd" style="display: none"></td>'
                        , '<td>'
                        , '<button type="button" class="layui-btn layui-btn-xs demo-up layui-btn-normal" style="display: none">上传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger submitlist demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个上传
                    tr.find('.demo-up').on('click', function () {
                        //接收token
                        var token = "";
                        //接受随机文件名
                        var rondomName = "";
                        var suffix = file.name.substring(file.name.lastIndexOf("."), file.name.length);//获取文件后缀
                        // obj.upload(index, file);
                        $.ajax({
                            type: 'post',
                            url: "${base}/chLorePoint/getUploadToken",
                            data: {"suffix": suffix},
                            async: false,
                            dataType: 'json',
                            success: function (res) {
                                console.log(res);
                                if (res.success) {
                                    token = res.data.token;
                                    rondomName = res.data.filename;//随机文件名
                                } else {
                                    layer.msg(res.message);
                                    delete files[index]; //删除对应的文件
                                    tr.remove();
                                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                                }
                            }
                        });
                        fileUpload(index, file, token, rondomName);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });
                    var num = index.split("-")[1];
                    num = parseInt(num);
                    if(num<1){
                        $("#selectvedio").addClass('layui-btn-disabled').attr('disabled', "true");
                        $("#upList").append(tr);
                        var url = URL.createObjectURL(file);//把file转成URL
                        $('#videoattr').attr('src', url); //视频链接
                        $("#videoUrl").attr("value", "new");
                    }
                });
            }
        });


        /**
         * 上传七牛云核心代码
         * @param index 文件下表
         * @param file  文件对象
         * @param token 凭证
         * @param randomName 接口生成的随机文件名，之后用来当作文件地址
         */
        function fileUpload(index, file, token, randomName) {

            var fileName = file.name;                                //上传的本地文件绝对路径
            var size = file.size > 1024 ? file.size / 1024 > 1024 ? file.size / (1024 * 1024) > 1024 ? (file.size / (1024 * 1024 * 1024)).toFixed(2) + 'GB' : (file.size
                / (1024 * 1024)).toFixed(2) + 'MB' : (file.size
                / 1024).toFixed(2) + 'KB' : (file.size).toFixed(2) + 'B';		//文件上传大小
            var tr = $("#upList").find("tr#upload-" + index);
            var tds = tr.children();
            tds.eq(3).find(".demo-up").attr('disabled', "true");
            //七牛云上传
            var observer = {                         //设置上传过程的监听函数
                next(res) {                        //上传中(result参数带有total字段的 object，包含loaded、total、percent三个属性)
                    var upview = Math.floor(res.total.percent); //查看进度[loaded:已上传大小(字节);total:本次上传总大小;percent:当前上传进度(0-100)]
                    tds.eq(2).html('<span style="color: #dbd90c;">正在上传-(' + upview + '%) </span>');

                },
                error(err) {
                    tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');                  //失败后
                },
                complete(res1) {                      //成功后
                    //****:填写你的绑定域名或七牛云提供的测试域名
                    //?imageView2/2/h/100：展示缩略图，不加显示原图
                    tds.eq(0).html(randomName);
                    tds.eq(2).html('<span style="color: #00db4f;">上传成功</span>');
                    tds.eq(3).find(".demo-delete").removeClass("layui-btn-disabled").removeAttr("disabled");
                    $(".submitlist").removeClass('layui-btn-disabled').removeAttr('disabled', "true");
                    formData.field.videoUrl = randomName;
                    var video_time = document.getElementById("videoattr").duration;//视频时长
                    formData.field.videoTimeLong = parseInt(video_time);
                    //编辑知识点
                    var addIndex = parent.layer.getFrameIndex(window.name);
                    $.post("${base}/chLorePoint/add", formData.field, function (res) {
                        if (res.success) {
                            parent.layer.msg("添加成功！", {time: 1000}, function () {
                                    parent.layer.close(addIndex);
                                    //刷新父页面
                                    parent.layui.table.reload('test');
                                }
                            );
                        } else {
                            layer.msg(res.message);
                        }
                    });
                }
            };
            var putExtra = {
                fname: randomName,                          //原文件名
                params: {},                         //用来放置自定义变量
                mimeType: null                      //限制上传文件类型
            };
            var config = {             //存储区域(z0: 代表华东;不写默认自动识别)
                concurrentRequestLimit: 3            //分片上传的并发请求量
            };
            var observable = qiniu.upload(file, randomName, token, putExtra, config);
            observable.subscribe(observer)          // 上传开始
        }

        // $(".submitlist").addClass('layui-btn-disabled').attr('disabled', "true");
        var formData;
        form.on("submit(addChLorePoint)", function (data) {
            if($("#upList").find("tr").length>1){
                layer.msg("只能上传一个视频！！！",{anim:6});
                return false;
            }
            var videoUrl = $("#videoUrl").attr("value");
            if (videoUrl != "" && videoUrl != null) {
                formData = data;
                $(".submitlist").addClass('layui-btn-disabled').attr('disabled', "true");
                $(".demo-up").click();
            } else {
                layer.msg("视频不能为空！！", {anim: 6});
            }
            return false;
        });

    });
</script>
</body>
</html>